package com.heakey.common.redis.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.event.cache.iface.INamespaceCacheManager;
import com.event.cache.model.NamespaceCacheKey;
import com.event.cache.util.CacheKeyParserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.lang.Nullable;

/**
 * @Description 自定义RedisCache
 * @Author Bing
 * @Date 2025/1/16 9:39
 */
@Slf4j
public class CustomRedisCache extends RedisCache {

    private String name;

    private INamespaceCacheManager namespaceCacheManager;

    public CustomRedisCache(INamespaceCacheManager namespaceCacheManager, String name, RedisCacheWriter cacheWriter, RedisCacheConfiguration cacheConfig) {
        super(name, cacheWriter, cacheConfig);
        this.name = name;
        this.namespaceCacheManager = namespaceCacheManager;
    }

    @Nullable
    public ValueWrapper get(Object key){
        try {
            String cacheKey = getCacheKey(key);
            if(ObjectUtil.isNull(namespaceCacheManager)){
                return super.get(key);
            }
            NamespaceCacheKey namespaceCacheKey = CacheKeyParserUtil.parseNamespaceKey(cacheKey);
            if(ObjectUtil.isNull(namespaceCacheKey)){
                return super.get(key);
            }
            // 注册
            namespaceCacheManager.register(namespaceCacheKey.parseRegister());
        }catch (Exception e){
            log.warn("RedisCache获取缓存异常",e);
        }
        return super.get(key);
    }

    private String getCacheKey(Object key){
        if(StrUtil.isBlank(name)){
            return key.toString();
        }
        StringBuilder sb = new StringBuilder(name);
        sb.append(RedisCacheConfig.PREFIX_TAG).append(key);
        return sb.toString();
    }
}